#!/bin/bash

base_path="/opt/shells/maxminddb"
csv_path="$base_path/GeoLite2-City-csv"
csv1="city_name.csv"
mkdir -p  "$base_path/zip"
mkdir -p  "$base_path/temp"
mkdir -p "$csv_path"
# 许可证
key=""

if [[  -n "$1" ]]; then
 key="$1"
fi
# 下载文件
 wget  "https://download.maxmind.com/app/geoip_download?edition_id=GeoLite2-City-CSV&license_key=$key&suffix=zip" -O "$base_path/zip/GeoLite2-City.zip"
if [[ ! -f "$base_path/zip/GeoLite2-City.zip" ]]; then
 echo "找不到文件:$base_path/zip/GeoLite2-City.zip"
 exit 1
fi 
if [[ ! -s "$base_path/zip/GeoLite2-City.zip" ]]; then
 echo "文件未下载完成:$base_path/zip/GeoLite2-City.zip"
 exit 1
fi
# 解压
 rm -rf "$csv_path/*"
 unzip -d "$csv_path" "$base_path/zip/GeoLite2-City.zip" 

# 筛选中国城市
csv_name=$(find $csv_path -name "GeoLite2-*zh-CN.csv" -type f)
awk -F, '
$6 == "中国" {
    desc = $6
    if ($8 != "") {
        desc = $6 "-" $8
    }
    if ($11 != "") {
        desc = desc "-" $11
    }
    print $1 "," desc
}' "$csv_name" > "$base_path/$csv1"

# 根据城市的id查询ip
ipv4_csv=$(find $csv_path -name "GeoLite2-*IPv4.csv" -type f)
city_ip="city_ip.csv"
city_code="city_code.csv"
awk -F, '
NR==FNR {
    # 将 geoname_id 作为键，描述信息作为值存入 ids 数组
    if ($1 != "" && $2 != "") {
        ids[$1] = $2
    }
    next
}
$2 in ids {
    desc = ids[$2]
    # 打印 IP 网络段和对应的描述信息
    print $1 "," desc
}' "$base_path/$csv1" "$ipv4_csv" > "$base_path/$city_ip"

# 筛选没有设置过自增id的城市
if [ ! -f "$base_path/$city_code" ];then
 awk -F, '!seen[$2]++ {print  $2}' "$base_path/$city_ip"| sort  |awk '{print ++count "," $1 }'|sort -t, -k1,1n >"$base_path/$city_code"
fi

cut -d',' -f2 "$base_path/$city_code"|sort|uniq>"$base_path/temp/uniq_$city_code"
cut -d',' -f2 "$base_path/$city_ip"|sort|uniq>"$base_path/temp/uniq_$city_ip"
comm -3 "$base_path/temp/uniq_$city_code" "$base_path/temp/uniq_$city_ip" >"$base_path/temp/col2_diff.txt"
# 保存没有设置自增id的城市
readarray -t  cityarray < <(awk '{if ($0 ~ /^\t/) print substr($0, 2)}' "$base_path/temp/col2_diff.txt") 
last_id=$(tail -n 1 "$base_path/$city_code" | cut -d',' -f1)
if [[ -z "$last_id" ]]; then
    last_id=0
fi
for line in "${cityarray[@]}";do
        ((last_id++))
 echo "$last_id,$line">> "$base_path/$city_code"
done

# 用cn_id作为ipset集合名将城市和ip保存到临时文件
echo &>"$base_path/temp/temp_ipset.txt"

while IFS=, read -r id name;do
readarray -t ip< <( grep $name "$base_path/city_ip.csv"|awk -F, '{print $1}')
if ! ipset list "cn_$id" &>/dev/null;then
ipset create "cn_$id" hash:net comment
fi
# ipset flush "cn_$id"
for i in "${ip[@]}"; do
# ipset add -exist "cn_$id" "$i" comment $name
echo "add cn_$id $i comment \"$name\" -exist" >> "$base_path/temp/temp_ipset.txt"
done
done<"$base_path/city_code.csv"

# 将临时文件更新进ipset
ipset restore <"$base_path/temp/temp_ipset.txt"